package com.locatme.fragmentmaps;

import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.locatme.model.Enseigne;
import com.locatme.model.Personne;
import com.locatme.model.Utilisateur;
import com.locatme.modelBD.UtilisateurBD;
import com.main.locatme.R;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;


public class MapsFragment extends Fragment implements LocationListener,
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener{

    private SupportMapFragment fragment;
    private GoogleMap map;
    private View view;
    private LocationRequest lr;
    private LocationClient lc;
    private UtilisateurBD userBD;

    private LayoutInflater inflater;
    private MapsCustomInfoWindow infoWindow;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
        }
        try {
            view= inflater.inflate(R.layout.fragment_map, container, false);
            this.inflater=inflater;
        } catch (InflateException e) {
            Toast.makeText(getActivity(), "Problems inflating the view !",
                    Toast.LENGTH_LONG).show();
        }
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        FragmentManager fm = getChildFragmentManager();
        fragment = (SupportMapFragment) fm.findFragmentById(R.id.map);
        if (fragment == null || !fragment.isAdded()) {
            fragment = SupportMapFragment.newInstance();
            lr = LocationRequest.create();
            lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            lc = new LocationClient(this.getActivity().getApplicationContext(),
                    this, this);
            lc.connect();

        }
        fm.beginTransaction().detach(fragment).replace(R.id.map, fragment).attach(fragment)
                .addToBackStack(null).commit();


    }

    @Override
    public void onResume() {
        super.onResume();

        if (map == null) {
            try {
                map = fragment.getMap();
                map.getUiSettings().setAllGesturesEnabled(true);
                map.getUiSettings().setMyLocationButtonEnabled(true);
                map.setMyLocationEnabled(true);
                map.getUiSettings().setZoomControlsEnabled(true);
                addMarkersToMap();
            } catch (NullPointerException e) {
                Toast.makeText(getActivity(), "Google Play Services missing !",
                        Toast.LENGTH_LONG).show();
            }
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();

        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            Log.e("log_tag", "NoSuchFieldException " + e.toString());

        } catch (IllegalAccessException e) {
            Log.e("log_tag", "IllegalAccessException " + e.toString());
        }
    }

    @Override
    public void onDestroyView()
    {
        if ((getActivity() != null) && (getActivity().isFinishing() != true)) {
            Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
            FragmentManager fm = getActivity().getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            try{
                ft.remove(fragment);
                ft.commitAllowingStateLoss();

            }catch (Exception e)
            {
                Log.e("Log_map",e.toString());
            }
        }

        super.onDestroyView();

    }


    @Override
    public void onLocationChanged(Location l2) {
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
                new LatLng(l2.getLatitude(), l2.getLongitude()), 15);
        map.animateCamera(cameraUpdate);
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {

    }

    @Override
    public void onConnected(Bundle connectionHint) {
        lc.requestLocationUpdates(lr, this);

    }

    @Override
    public void onDisconnected() {

    }

    private void addMarkersToMap() {
        BitmapDescriptor bitmapMarker;
        Utilisateur user;

        Iterator<Utilisateur> i;
        map.clear();
        List<Utilisateur> listPersLoca = null;
        List<Utilisateur> listEnseigLoca = null;
        userBD=new UtilisateurBD(getActivity());
        userBD.open();

        listPersLoca = userBD.getUserByType(1);



        if(listPersLoca!=null){
            i = listPersLoca.iterator();

            bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE);
            while(i.hasNext()){
                user = i.next();

                map.addMarker(new MarkerOptions()
                        .position(user.getLocalisation())
                        .title(((Personne) user).getPseudo())
                        .snippet(" parle : "+user.getAffLangues())
                        .icon(bitmapMarker));
            }
        } else {
            Toast.makeText(getActivity(), "Aucune personne aux alentours !",
                    Toast.LENGTH_LONG).show();
        }


        listEnseigLoca = userBD.getUserByType(2);

        if(listEnseigLoca!=null){
            i = listEnseigLoca.iterator();
            bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
            while(i.hasNext()){
                user = i.next();

                map.addMarker(new MarkerOptions()
                        .position(user.getLocalisation())
                        .title(((Enseigne) user).getNomEnseigne())
                        .snippet(" parle : "+user.getAffLangues())
                        .icon(bitmapMarker));
            }
        } else {
            Toast.makeText(getActivity(), "Aucune enseigne aux alentours !",
                    Toast.LENGTH_LONG).show();
        }
    }


}
